import React from "react";
import { PureComponent } from "react";
import "./_style.less";
import _ from "lodash";
import { getDsToZlData, getDesignTableInfoByTidApi, } from "../ExcelGrid/api/DesignTableApi";
import { parseFormulaByContentApi } from "../ExcelGrid/api/DesignTableApi";
import { nanoid10 } from "../../tools/Tools";
export var E_CpasTableDescCategory;
(function (E_CpasTableDescCategory) {
    E_CpasTableDescCategory["DC"] = "disclosureContent";
    E_CpasTableDescCategory["DCN"] = "disclosureContentNote";
    E_CpasTableDescCategory["ZL_DC"] = "zlDisclosureContent";
    E_CpasTableDescCategory["ZL_DCN"] = "zlDisclosureContentNote";
})(E_CpasTableDescCategory || (E_CpasTableDescCategory = {}));
const XMType = window.sessionStorage.electronParams
    ? JSON.parse(window.sessionStorage.electronParams)?.params?.XMType
    : "单机审计项目";
//整理模式双表header对比计算
function diffHeaderData(newHeaderData, header) {
    newHeaderData = newHeaderData.slice(0);
    header = header.slice(0);
    if (header.length && newHeaderData.length) {
        for (let i = 0; i < newHeaderData.length; i++) {
            const dsItem = newHeaderData[i];
            for (let j = 0; j < header.length; j++) {
                const zlItem = header[j];
                const zlKey = zlItem?.key;
                const zlKeyRes = zlKey.indexOf("-zl") !== -1
                    ? zlKey.slice(0, zlKey.length - 3)
                    : zlKey;
                console.log(zlKeyRes, "zlKeyRes---", dsItem?.key === zlKeyRes);
                if (dsItem && zlItem && dsItem?.key === zlKeyRes) {
                    dsItem.config.width = zlItem?.config?.width || 150;
                    if (dsItem.children && zlItem.children) {
                        const data = diffHeaderData(dsItem.children, zlItem.children);
                        dsItem.children = data;
                    }
                }
            }
        }
    }
    return newHeaderData;
}
/**
 *
 * import CpasTableInput from  "~/public/cpas-ui/components-bs/HandsonTable"
 *
 */
class DsBase extends PureComponent {
    vsTableRef = React.createRef(); //容器Ref
    zlTableRef = React.createRef(); //容器Ref
    //标题注解ref
    titleEditorRef = React.createRef();
    //内容注解ref
    contentEditorRef = React.createRef();
    cpasstableWapperRef = React.createRef();
    zlCpasTableRef = [];
    constructor(props) {
        super(props);
        console.log("props--", props);
        this.state = {
            isShowDsMenuBar: false,
            isShowZlMenuBar: false,
            isOpenDetails: false,
            showDismantledTable: false,
            result: [],
            resultList: [],
            tabValue: "1",
            isBackAll: false,
            zlCpasTable: [],
            reCalculateFormulaLoading: false,
            reSyncLoading: false,
        };
        this.onShowDetailsModal = this.onShowDetailsModal.bind(this);
        this.tabModelChanges = this.tabModelChanges.bind(this);
        this.onFocusOutCallback = this.onFocusOutCallback.bind(this);
        this.setZlCpasTableRefs = this.setZlCpasTableRefs.bind(this);
        this.beforeJsonExport = this.beforeJsonExport.bind(this);
        this.beforeJsonImport = this.beforeJsonImport.bind(this);
        this.handleCustomEvent = this.handleCustomEvent.bind(this);
    }
    // saveDismantleAndHideSession = (zlTableConfig) => {
    //   if (zlTableConfig?.rule) {
    //     sessionStorage.rule = JSON.stringify(zlTableConfig?.rule);
    //     sessionStorage.dismantleTableMode = JSON.stringify(true);
    //   }
    //   if (zlTableConfig?.hideColumnArr) {
    //     sessionStorage.hideColumnArr = JSON.stringify(
    //       zlTableConfig?.hideColumnArr
    //     );
    //     sessionStorage.hideColumnKeyArr = JSON.stringify(
    //       zlTableConfig?.hideColumnKeyArr
    //     );
    //   }
    // };
    beforeJsonImport(cpasData) {
        let { zlTableConfig, zlArtFormula, zlHeader } = cpasData;
        if (typeof zlTableConfig === "string") {
            zlTableConfig = JSON.parse(zlTableConfig);
        }
        this.zlTableRef.current.tableConfig = zlTableConfig;
        if (zlArtFormula) {
            this.zlTableRef.current.articulationVerifyService.artVerifyFormulaList =
                zlArtFormula;
        }
        if (zlHeader) {
            this.zlTableRef.current.zlHeader = zlHeader;
        }
    }
    beforeJsonExport(cpasData) {
        cpasData["zlTableConfig"] = this.zlTableRef.current?.tableConfig;
        cpasData["zlArtFormula"] =
            this.zlTableRef.current?.articulationVerifyService.artVerifyFormulaList;
        const zl_header = this.getZlAllHeaders();
        if (zl_header) {
            cpasData["zlHeader"] = zl_header;
        }
        return cpasData;
    }
    getFormulaSourceData() {
        const dsTableRef = this.props.innerRef;
        return dsTableRef.current?.getCpasTableGrid();
    }
    setZlCpasTableRefs = (value) => {
        this.setState({
            zlCpasTable: value,
        });
    };
    setDSVerifyResult = (result) => {
        this.setState({
            result,
        });
    };
    tabModelChanges = async (value) => {
        this.setState({
            tabValue: value,
        });
        const dsTableRef = this.props.innerRef;
        const { tid = "", status_name = "" } = this.props.notes
            ? this.props.notes
            : {};
        //2整理模式
        if (value === "2") {
            let getTableData = {};
            //重置节点状态e
            if (this.props?.initContent) {
                this.props?.initContent(true);
            }
            let zlContent = this.getContentEditorContent();
            const contentTitle = this.getTitleEditorContent();
            this.setTitleEditorPreviewContent(contentTitle);
            if (zlContent) {
                const displayData = dsTableRef.current?.hot.getData();
                const zlContentNoteResponse = await parseFormulaByContentApi({
                    content: zlContent,
                    displayData,
                });
                if (zlContentNoteResponse.ok) {
                    zlContent = zlContentNoteResponse.data;
                }
                this.setContentEditorPreviewContent(zlContent);
            }
            else {
                this.setContentEditorPreviewContent(zlContent);
            }
            const dataFrom = dsTableRef.current?.dataFrom;
            //从数据库获取tableConfig数据
            if (dataFrom === "server" && tid) {
                getTableData = await getDesignTableInfoByTidApi(`${tid}-zl`, "zl", "json");
            }
            // 0.先查询远程数据库中的tableConfig [object Object]
            const remoteTableConfig = getTableData?.data?.tableConfig &&
                getTableData?.data?.tableConfig !== "[object Object]"
                ? JSON.parse(getTableData?.data?.tableConfig)
                : {};
            // 1.获取当前整理模式下的最新的tableConfig
            let zlTableConfig = {
                ...remoteTableConfig,
                ...this.zlTableRef.current?.tableConfig,
            };
            //TODO 这里其实不用这么做，只要保证resetTable重置掉整理下的tableConfig就可以了
            //目前暂不做调整
            if (status_name === "add" && dataFrom !== "import") {
                zlTableConfig = {};
            }
            if (!zlTableConfig.directionCfg) {
                zlTableConfig.directionCfg = {
                    direction: "vertical",
                };
            }
            const remoteHeaderData = getTableData?.data?.header;
            console.log(remoteTableConfig, "remote tableConfig");
            console.log(this.zlTableRef.current?.tableConfig, "-----zl tableConfig---");
            console.log(zlTableConfig, "merge tableConfig");
            if (this.zlTableRef.current) {
                this.zlTableRef.current.tableConfig = zlTableConfig;
            }
            // 2. 获取披露表最新数据
            const getDsTableSourceData = dsTableRef.current?.getCpasTableGrid();
            let getDsTableData = dsTableRef.current?.getCpasTableGrid("display", null, false);
            // // 过滤运行时列
            // getDsTableData = await dsTableRef.current?.filterRunTimeColumn(
            //   getDsTableData
            // );
            //用整理模式下的header数据&&整理模式下的宽度用自己的
            if (remoteHeaderData && remoteHeaderData.length) {
                const newHeaderData = diffHeaderData(getDsTableData?.header, remoteHeaderData);
                getDsTableData.header = newHeaderData;
            }
            //如果是json导入的数据，json导入的时候会将最新的zlHeader注入到 headerData中
            if (dataFrom === "import" && this.zlTableRef.current?.zlHeader) {
                const newHeaderData = diffHeaderData(getDsTableData?.header, this.zlTableRef.current?.zlHeader);
                getDsTableData.header = newHeaderData;
            }
            // 处理用户导入json文件，然后切换到整理模式时不隐藏和拆表问题
            const zlTableConfigKeyArr = Object.keys(zlTableConfig);
            if (zlTableConfigKeyArr.length === 0) {
                zlTableConfig = getDsTableData.tableConfig;
            }
            // 把拆表条件和隐藏列存到session中
            // this.saveDismantleAndHideSession(zlTableConfig);
            //cpastable中data项目列有跟模版参照行的数据重复，需要处理默认归并@0826邵宏提的需求
            // const rowMergeCfg = this.autoMergeData(
            //   zlTableConfig?.rowMergeCfg,
            //   getDsTableData?.data
            // );
            // if (zlTableConfig?.rowMergeCfg) {
            //   zlTableConfig.rowMergeCfg = rowMergeCfg;
            // }
            // 3. 调用数转服务
            try {
                const zlTableData = await getDsToZlData(getDsTableData, zlTableConfig, getDsTableSourceData, tid);
                if (getDsTableData && zlTableData.data) {
                    const zlTransformData = zlTableData.data;
                    //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                    //zlDivideData 拆表后的转数逻辑
                    //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                    const { zlGridData, zlDivideData } = zlTransformData;
                    //原表非拆表后的数据
                    await this.zlTableRef.current?.reloadTable(zlGridData, "zl", getDsTableData);
                    const res = await this.zlTableRef.current.afterDivideTableRender(zlDivideData, {
                        titleEditorVal: this.getTitleEditorPreviewContent(),
                        contentEditorVal: this.getContentEditorPreviewContent(),
                    });
                    //更新整理模式下cpastable实例
                    this.setZlCpasTableRefs(res);
                    this?.props?.setNoteVerifyResult &&
                        this?.props?.setNoteVerifyResult(this?.zlTableRef?.current?.articulationVerifyService
                            ?.artParseResultList);
                    this.zlTableRef?.current?.menuToolRef?.current?.reductionEditorRef?.current?.setIsHiddenMergeRow(this?.zlTableRef.current?.tableConfig?.filterCfg?.num ? true : false);
                }
            }
            catch (e) {
                throw e;
            }
        }
        // if (value === "3") {
        //   const dsTableSourceData = dsTableRef.current?.getCpasTableGrid();
        //   try {
        //     const res = await getDsToTZData(dsTableSourceData, tid, true);
        //     await this.vsTableRef.current?.reloadTable(res, "ds", res?.tableConfig);
        //   } catch (e) {
        //     console.log(e);
        //   }
        // }
    };
    //整理模式归并项目列重复自动归并
    autoMergeData(rowMergeCfg, data) {
        if (!rowMergeCfg || !rowMergeCfg?.rowsData) {
            return rowMergeCfg;
        }
        const rowsData = rowMergeCfg?.rowsData;
        if (rowsData && rowsData.length) {
            let mergeRow = [];
            for (let i = 0; i < rowsData.length; i++) {
                let { value, rowValues, cellData, columnNum, mergeRowIds } = rowsData[i];
                const isRepeatData = data.filter((rows) => rows[columnNum] === value); //判断data中有没有跟模版参照行重复的数据
                const isTrue = rowValues.includes(value); //是否勾选
                if (isRepeatData && isRepeatData.length && !isTrue) {
                    const currentData = isRepeatData[0];
                    const currentStr = currentData[currentData.length - 1];
                    const currentCfg = currentStr ? JSON.parse(currentStr) : {};
                    const rId = currentCfg?.rId ? currentCfg.rId : nanoid10();
                    rowValues.push(currentData[columnNum]);
                    cellData.push(currentData[columnNum]);
                    mergeRowIds.push(rId);
                    rowsData[i]["rowValues"] = rowValues;
                    rowsData[i]["cellData"] = cellData;
                    rowsData[i]["mergeRowIds"] = mergeRowIds;
                }
                mergeRow.push(mergeRowIds);
            }
            rowMergeCfg["rowsData"] = rowsData;
            rowMergeCfg["mergeRow"] = mergeRow;
        }
        return rowMergeCfg;
    }
    //获取标题注解内容
    getTitleEditorContent = () => {
        const titleEditorRef = this.titleEditorRef.current;
        return titleEditorRef?.getData();
    };
    //获取内容注解内容
    getContentEditorContent = () => {
        const contentEditorRef = this.contentEditorRef.current;
        return contentEditorRef?.getData();
    };
    //设置标题注解内容
    setTitleEditorContent = (data) => {
        const titleEditorRef = this.titleEditorRef.current;
        titleEditorRef?.setData(data);
    };
    //设置内容注解内容
    setContentEditorContent = (data) => {
        const contentEditorRef = this.contentEditorRef.current;
        contentEditorRef?.setData(data);
    };
    //获取预览内容注解内容（解析公式后的数据）
    getContentEditorPreviewContent = () => {
        const contentEditorRef = this.contentEditorRef.current;
        return contentEditorRef?.getPreviewData();
    };
    //获取标题注解预览内容（解析公式后的数据）
    getTitleEditorPreviewContent = () => {
        const titleEditorRef = this.titleEditorRef.current;
        return titleEditorRef?.getPreviewData();
    };
    //设置预览标题注解内容
    setTitleEditorPreviewContent = (data) => {
        const titleEditorRef = this.titleEditorRef.current;
        titleEditorRef?.setPreviewData(data);
    };
    //设置预览内容注解内容
    setContentEditorPreviewContent = (data) => {
        const contentEditorRef = this.contentEditorRef.current;
        contentEditorRef?.setPreviewData(data);
    };
    onFocusOutCallback = (type) => {
        const dsTableRef = this.props.innerRef.current;
        let value = this.getTitleEditorContent();
        if (type === "content") {
            value = this.getContentEditorContent();
        }
        dsTableRef &&
            dsTableRef.setTableContentChange(true, {
                type: type === "content" ? "修改批露注释" : "修改批露内容",
                params: {
                    value,
                },
            });
    };
    //获取整理模式下所有cpastable的header
    getZlAllHeaders() {
        const zlCpasTables = this.state.zlCpasTable;
        let allHeaders = [];
        if (zlCpasTables && zlCpasTables.length) {
            for (let i = 0; i < zlCpasTables.length; i++) {
                const cpasRef = zlCpasTables[i];
                const cpasIGridData = cpasRef?.getCpasTableGrid();
                if (cpasIGridData?.header) {
                    allHeaders = [...allHeaders, ...cpasIGridData?.header];
                }
            }
        }
        return allHeaders;
    }
    //保存双表数据
    commonSaveData = async (name, tid, data_id, action, isThirdTable) => {
        const dsTableRef = this.props.innerRef;
        const zlTableRef = this.zlTableRef.current;
        const dsTableData = dsTableRef.current?.getCpasTableGrid("display");
        const dsTableSourceData = dsTableRef.current?.getCpasTableGrid();
        const zlCpasTables = this.state.zlCpasTable;
        const contentTitle = this.getTitleEditorContent();
        const content = this.getContentEditorContent();
        let dsCpasDesc = [];
        if (action !== "add") {
            const contentTitleDesc = {
                tid,
                category: E_CpasTableDescCategory.DC,
                describe: contentTitle,
            };
            const contentDesc = {
                tid,
                category: E_CpasTableDescCategory.DCN,
                describe: content,
            };
            if (contentTitle) {
                dsCpasDesc.push(contentTitleDesc);
            }
            if (content) {
                dsCpasDesc.push(contentDesc);
            }
        }
        //是否需要保存三表。合并系统调整数的表需要保存三表
        if (isThirdTable) {
            const res = await dsTableRef.current?.saveToServerMerge(name, "ds", tid, data_id, dsCpasDesc);
            if (!res) {
                return "流程异常";
            }
        }
        else {
            const res = await dsTableRef.current?.saveToServer(name, "ds", tid, data_id, dsCpasDesc);
            if (!res) {
                return "流程异常";
            }
        }
        let getZLTableData = {};
        if (tid) {
            getZLTableData = await getDesignTableInfoByTidApi(`${tid}-zl`, "zl", "json");
        }
        const tabValue = this.state.tabValue;
        if (zlTableRef) {
            const remoteConfig = getZLTableData?.data?.tableConfig &&
                getZLTableData?.data?.tableConfig !== "[object Object]"
                ? JSON.parse(getZLTableData?.data?.tableConfig)
                : {};
            let zlTableConfig = {
                ///...remoteConfig,
                ...zlTableRef.getCpasTableGrid()?.tableConfig,
            };
            if (tabValue === "1") {
                zlTableConfig = {
                    ...remoteConfig,
                    ...zlTableRef.getCpasTableGrid()?.tableConfig,
                };
            }
            if (zlTableConfig && !zlTableConfig.directionCfg) {
                zlTableConfig["directionCfg"] = {
                    direction: "vertical",
                };
            }
            let header = [];
            let allHeaders = []; //通过cpastable 实例获取header
            const contentText = this?.props?.contentText || false;
            //节点切换兼容处理---无操作过tab页&&并且在附注的页签
            if (!contentText && tabValue === "1" && getZLTableData?.data?.header) {
                header = getZLTableData?.data?.header.slice(0);
            }
            else if (zlCpasTables.length) {
                for (let i = 0; i < zlCpasTables.length; i++) {
                    const cpasRef = zlCpasTables[i];
                    const cpasIGridData = cpasRef?.getCpasTableGrid();
                    if (cpasIGridData?.header) {
                        allHeaders = [...allHeaders, ...cpasIGridData?.header];
                    }
                }
                header = [...allHeaders];
            }
            const dsHeader = [...dsTableData.header];
            //整理模式&&批露表header对比，整理模式入库header的宽度以整理模式的为准
            //const newHeaderData = diffHeaderData(dsHeader, header);
            const newHeaderData = diffHeaderData(dsHeader, header);
            let zlTableGridData = { ...dsTableData };
            zlTableGridData["header"] = newHeaderData;
            let zlTableSourceGridData = _.cloneDeep(zlTableGridData);
            zlTableSourceGridData["data"] = dsTableSourceData.data;
            zlTableGridData["cpasDesc"] = dsCpasDesc;
            //调用数转接口，保证最新数据
            try {
                const zlTableData = await getDsToZlData(zlTableGridData, zlTableConfig, zlTableSourceGridData, tid, true);
                let zlGridData = zlTableData.data.zlGridData;
                zlGridData = await dsTableRef.current?.filterRunTimeColumn(zlGridData);
                //附注整体前保存需要刷一下整理后的数据
                if (tabValue === "1") {
                    await this.zlTableRef.current?.reloadTable(zlGridData, "zl", zlTableConfig);
                }
                await zlTableRef.saveToServerByCpasData(zlGridData, name, "zl", tid + "-zl", data_id);
            }
            catch (e) {
                throw e;
            }
        }
    };
    handleRemoveData = async (name, data_id) => {
        const dsTableRef = this.props.innerRef;
        const zlTableRef = this.zlTableRef.current;
        // tname, data_id, type
        await dsTableRef.current?.removeTableByServer(name, data_id, "ds");
        await zlTableRef.removeTableByServer(name, data_id, "zl");
    };
    handleSetTabValue = () => {
        this.setState({
            tabValue: "1",
        });
    };
    handleCustomEvent(event) {
        this.setState({
            isOpenDetails: false,
        });
    }
    componentDidMount() {
        // 定义事件处理函数
        // 监听自定义事件
        document.addEventListener("closeDetail", this.handleCustomEvent);
    }
    componentWillUnmount() {
        document.removeEventListener("closeDetail", this.handleCustomEvent);
    }
    //数据同步
    handleSyncData = () => { };
    onShowDetailsModal = () => {
        // 当开启的时候, 默认通知所有进行关闭
        if (!this.state.isOpenDetails) {
            const customEvent = new CustomEvent("closeDetail", {
                detail: {
                    message: "close",
                },
            });
            document.dispatchEvent(customEvent);
            // 同步一下父组件的状态,和自定义组件的状态
            this.setState({
                isOpenDetails: false,
            });
            setTimeout(() => {
                // 等待自定义通知完成
                this.setState({
                    isOpenDetails: true,
                });
            }, 50);
        }
        else {
            this.setState({
                isOpenDetails: !this.state.isOpenDetails,
            });
        }
    };
    onBackAll = () => {
        this.setState({
            isBackAll: false,
        });
    };
    onShowBar = () => {
        this.setState({
            isShowDsMenuBar: false,
            isShowZlMenuBar: false,
        });
    };
}
export default DsBase;
